package com.woniu.staff.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.model.Result;
import com.woniu.staff.cliententity.model.Account;
import com.woniu.staff.param.*;
import com.woniu.staff.util.JWTUtil;
import com.woniu.staff.dto.EmployeeDto;
import com.woniu.staff.form.*;
import com.woniu.staff.model.Employee;
import com.woniu.staff.service.EmployeeService;
import com.woniu.staff.util.RedisUtil;
import com.woniu.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.ibatis.annotations.Insert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.ElementType;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *员工接口
 * @author 吴彦祖
 * @since 2024年05月23日
 */

@RestController
@RequestMapping("/employee")
@Api(tags = "员工接口")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @Resource
    private RedisUtil redisUtil;

    /**
     * 新增员工
     * @param form 新增员工的form对象
     * @return 新增成功输出成功的员工对象失败为空抛异常
     * @throws Exception
     */
    @ApiOperation("新增员工")
    @PostMapping("addEmployee")
    public Result addEmployee(@RequestBody AddEmployeeForm form) throws Exception {
//        System.out.println(JSONUtil.toJsonStr(form));
        Employee employee = employeeService.insert(form);
//        System.out.println(JSONUtil.toJsonStr(Result.newInstance(Employee.class).setData(employee).setMessage("新增员工成功")));
        return Result.newInstance(Employee.class).setData(employee).setMessage("新增员工成功");
    }



    /**
     * 新增站长
     * @param form 新增员工的form对象
     * @return 新增成功输出成功的员工对象失败为空抛异常
     * @throws Exception
     */
    @ApiOperation("新增站长")
    @PostMapping("addStationBoss")
    public Result addStationBoss(@RequestBody AddStationBossForm form) throws Exception {
//        System.out.println(JSONUtil.toJsonStr(form));
        Employee employee = employeeService.addStationBoss(form);
//        System.out.println(JSONUtil.toJsonStr(Result.newInstance(Employee.class).setData(employee).setMessage("新增员工成功")));
        return Result.newInstance(Employee.class).setData(employee).setMessage("新增站长成功");
    }

    /**
     * 根据员工id修改员工信息
     * @param form 包含员工id 和修改内容
     * @return 成功输出员工修改后对象
     */
    @ApiOperation("根据员工id修改员工信息")
    @PostMapping("/updateEmployee")
    public Result updateEmployee(@RequestBody UpdateEmployeeForm form){

        return Result.newInstance(Employee.class).setMessage("修改成功");
    }

    /**
     * 根据站点id和状态查询相应的员工信息 无状态则查站点全部员工
     * @param form 站点id  和状态id
     * @return 输出查询到的员工对象集合
     */
    @ApiImplicitParam(name = "stationId",value = "站点id")
    @GetMapping("/findAllByStationId")
    @ApiOperation("根据站点id和状态id查询相应的员工")
    public Result<Page> findAllByStationId(FindAllStateEmployeeForm form){
        Page<Employee> employees = employeeService.findAllByStationId(BeanUtil.toBean(form, FindAllStateEmployeeParam.class));
        return Result.newInstance(Page.class).setData(employees).setMessage("查询成功");
    }

    /**
     * 根据站点id查询全部员工(站点负责人除外)
     * @param pageNum,pageSize 分页参数
     * @return 输出查询到的员工对象集合
     */
    @ApiImplicitParam(name = "id",value = "站点id")
    @GetMapping("/findAllByStationIdWithoutHandler")
    @ApiOperation("根据站点id查询全部员工(站点负责人除外)")
    public Result<Page<Employee>> findAllByStationIdWithoutHandler(@RequestHeader String token,@RequestParam("pageNum") Integer pageNum,@RequestParam("pageSize")  Integer pageSize) throws Exception {
        String refreshToken = redisUtil.get(token);
        int handlerId = Integer.parseInt(JwtUtil.parseToken(refreshToken,JwtUtil.stationBossSecret).get("accountId").toString());
        Page<Employee> employees = employeeService.findAllByStationIdWithoutHandler(handlerId,pageNum,pageSize);
        return Result.newPageInstance(Employee.class).setData(employees).setMessage("查询成功");
    }

    /**
     * 根据id查询员工是否存在
     * @param id 员工id
     * @return 输出查询到的员工对象集合
     */
    @ApiImplicitParam(name = "id",value = "员工id")
    @GetMapping("/checkById/{id}")
    @ApiOperation("根据id查询员工是否存在")
    public Result<Boolean> checkById(@PathVariable("id") String id) throws Exception {

        Boolean b = employeeService.getById(id) == null;
        return Result.newInstance(Boolean.class).setData(b).setMessage("查询成功");
    }

    /**
     * 修改员工状态
     * @param form 员工id 状态码
     * @return 返回修改成功后的员工对象dto
     * @throws Exception
     */
    @ApiOperation("修改员工状态")
    @PostMapping("/updateEmployeeState")
    public Result updateEmployeeState(@RequestBody UpdateEmployeeStateForm form) throws Exception {
        EmployeeDto dto = employeeService.UpdateEmployeeStateForm(BeanUtil.toBean(form, UpdateEmployeeStateParam.class));
        return Result.newInstance(EmployeeDto.class).setData(dto).setMessage("修改员工状态成功");
    }

    /**
     * 通过员工账号id修改员工载重量
     * @param form 员工账号id 载重量
     * @return 返回修改后的员工dto
     */
    @ApiOperation("通过员工账号id修改员工载重量")
    @PostMapping("/updateEmployeeLoad")
    public Result<EmployeeDto> updateEmployeeLoad(@RequestBody UpdateEmployeeLoadForm form){
        EmployeeDto dto = employeeService.updateEmployeeLoad(BeanUtil.toBean(form, UpdateEmployeeLoadParam.class));
        return Result.newInstance(EmployeeDto.class).setData(dto).setMessage("修改车工");
    }

//    /**
//     * 员工登录
//     * @param form 账号密码
//     * @param response 请求响应对象
//     * @return 输出登录对象
//     */
//    @PostMapping("/login")
//    public Result login(@RequestBody EmployeeLoginForm form, HttpServletResponse response){
//        System.out.println(form.toString());
//        EmployeeDto employeeDto= employeeService.login(BeanUtil.toBean(form, EmployeeLoginParam.class));
//        Account account=new Account();
//        account.setAccountId(employeeDto.getAccountId().intValue());
//        account.setAccountPhone(employeeDto.getAccount_phone());
//        Map<String, Object> map = BeanUtil.beanToMap(account);
//        HashMap<String,Object> accessBody =new HashMap<String,Object>();
//
//        //生成随机数 防止极端情况 绝对同一个时间
//        String random = new Snowflake(1, 1).nextIdStr();
//        accessBody.put("random",random);
////        生成jwt 24小时有效期 短token
//        //短token返回前端不包含敏感数据
//        String accessToken= JWTUtil.createToken(accessBody,15);
//        //长token返回Redis数据库包含敏感数据
//        String refreshToken= JWTUtil.createToken(map,3*24*60);
//        redisUtil.set(accessToken,refreshToken,3*24*60*60);
////        通过响应头将jwt响应给客户端
//        response.setHeader("token", accessToken);
////        在跨域请求访问时 必须公开该请求头 前端`才能获取到
//        response.setHeader("Access-Control-Expose-Headers","token");
//
//        return Result.newInstance(EmployeeDto.class).setData(employeeDto).setMessage("登录成功");
//    }

    /**
     * 分页查询所有可用的员工
     * @param form 分页对象
     * @return 分页page对象
     */
    @ApiOperation("分页查询所有可用的员工")
    @PostMapping("/findUsefulHandlerPage")
    public Result<Page<EmployeeDto>> findUsefulHandlerPage(@RequestBody PageForm form){
        Page<EmployeeDto> page =employeeService.findUsefulHandlerPage(BeanUtil.toBean(form, PageParam.class));
        return Result.newPageInstance(EmployeeDto.class).setData(page).setMessage("查询所有员工成功");
    }

    /**
     * 查询所有可用的员工
     * @return 所有状态为正常的员工
     */
    @ApiOperation("查询所有可用的员工")
    @GetMapping("/findUsefulHandler")
    public Result<List<EmployeeDto>> findUsefulHandler(){
        List<EmployeeDto> page =employeeService.findUsefulHandler();
        return Result.newListInstance(EmployeeDto.class).setData(page).setMessage("查询所有员工成功");
    }

    /**
     * 查询除一个员工外所有可用的员工
     * @return 除一个员工外所有可用的员工
     */
    @ApiOperation("查询除一个员工外所有可用的员工")
    @GetMapping("/findUsefulHandlerExcept/{employId}")
    public Result<List<EmployeeDto>> findUsefulHandlerExcept(@PathVariable Integer employId){
        List<EmployeeDto> page =employeeService.findUsefulHandlerExcept(employId);
        return Result.newListInstance(EmployeeDto.class).setData(page).setMessage("查询除一个员工外所有可用的员工成功");
    }



    /**
     * 查询除自己外的其他可用管理员id
     * @param id 管理员id
     * @return 管理员对象集合
     */
    @GetMapping("/showUsefulHandlerExceptOne/{id}")
    @ApiOperation("查询除自己外的其他可用管理员id")
    public Result<List<EmployeeDto>> showUsefulHandlerExceptOne(
            /*
            员工id
             */
            @ApiParam(name = "id",value = "员工id")
            @PathVariable("id")Integer id){

        List<EmployeeDto> dtos =employeeService.showUsefulHandlerExceptOne(id);


        return Result.newListInstance(EmployeeDto.class).setData(dtos).setMessage("查询除自己外的其他可用管理员成功");

    }



    /**
     * 开除员工
     * @param id 员工id
     */
    @GetMapping("/del/{id}")
    @ApiOperation("查询除自己外的其他可用管理员id")
    public Result<?> del(@PathVariable("id")Integer id){

        employeeService.del(id);


        return Result.newInstance(null).setMessage("开除员工成功!");

    }



    /**
     * 根据账号查询员工对象
     * @param accountId 账号id
     * @return 返回账号对象
     */
    @ApiOperation("根据账号id查询员工对象")
    @GetMapping("/findEmployeeByAccountId/{accountId}")
    public Result<EmployeeDto> findEmployeeByAccountId(
            /*
            账号id
             */
            @ApiParam(name = "accountId",value = "账号id")
            @PathVariable("accountId") String accountId
    ){
        EmployeeDto employee = employeeService.findEmployeeByAccountId(accountId);
        return Result.newInstance(EmployeeDto.class).setData(employee).setMessage("查询员工成功");
    }
    /**
     * 根据站点id 查询是否有除负责人外的员工
     * accountId 站点id
     * handlerId 负责人id
     * @return 有true 没有false
     */
    @GetMapping("/employee/isHaveEmploye/{stationId}/{handlerId}")
    public Result<Boolean> isHaveEmploye(@PathVariable("stationId") String accountId,@PathVariable("handlerId") String handlerId
    ){
        Boolean b =  employeeService.isHaveEmploye(accountId,handlerId);
        return Result.newInstance(Boolean.class).setData(b).setMessage("查询成功");
    }


    /**
     * 根据账号id查询员工实体
     * id 账号id
     */
    @GetMapping("/byAccountId/{id}")
    @ApiOperation("根据账号id查询员工实体")
    public Result<Employee> byAccountId(@PathVariable("id") @ApiParam("账号id") Integer id){
        Employee employee = employeeService.byAccountId(id);
        return Result.newInstance(Employee.class).setData(employee).setMessage("根据账号id查询员工实体成功");
    }

    /**
     * 根据员工id查询员工实体
     * id 员工id
     */
    @GetMapping("/byId/{id}")
    @ApiOperation("根据员工id查询员工实体")
    public Result<Employee> byId(@PathVariable("id") @ApiParam(name = "id",value = "员工id") Integer id){
        Employee employee = employeeService.byId(id);
        return Result.newInstance(Employee.class).setData(employee).setMessage("根据员工id查询员工实体成功");
    }

    /**
     * 根据站点id查询站长
     * @param stationId
     * @return
     */
    @GetMapping("/byStationId/{stationId}")
    @ApiOperation("根据站点id查询站长")
    public Result byStationId(
            @PathVariable("stationId")
            @ApiParam(name = "stationId",value = "站点id")
            String stationId){
        Employee employee =employeeService.byStationId(stationId);
        return Result.newInstance(Employee.class).setData(employee).setMessage("查询成功");
    }

    /**
     * 员工绑定站点
     * id 账号id roleId 角色id
     */
    @GetMapping("/bindingStation/{id}/{stationId}")
    @ApiOperation("员工绑定站点")
    Result<Employee> bindingStation(@PathVariable("id") Integer id,@PathVariable("stationId") Integer stationId){
        Employee employee =employeeService.bindingStation(id,stationId);
        return  Result.newInstance(Employee.class).setData(employee).setMessage("员工绑定站点成功");
    }

//    /**
//     * 新增员工
//     * @param form 员工信息
//     * @param token
//     * @return
//     * @throws Exception
//     */
//    @PostMapping("/addEmployeeUser")
//    @ApiOperation("新增员工")
//    public Result<Employee> addEmployeeUser(@RequestBody AddEmployeeUserForm form,@RequestHeader("token") String token) throws Exception {
//        String refreshToken = redisUtil.get(token);
//        Integer userId = Integer.parseInt(JwtUtil.parseToken(refreshToken,JwtUtil.stationBossSecret).get("accountId").toString());
//        Employee employee = employeeService.addEmployeeUser(userId,BeanUtil.toBean(form,AddEmployeeUserParam.class));
//        return Result.newInstance(Employee.class).setData(employee).setMessage("新增成功，初始密码：123456");
//    }

//    /**
//     * 新增员工
//     * @param form 员工信息
//     * @param token
//     * @return
//     * @throws Exception
//     */
//    @PostMapping("/addEmployeeStation")
//    @ApiOperation("新增站长")
//    public Result<Employee> addEmployeeStation(@RequestBody AddEmployeeUserForm form,@RequestHeader("token") String token) throws Exception {
//        String refreshToken = redisUtil.get(token);
//        String adminSecret = JwtUtil.adminSecret;
//        Claims claims = JwtUtil.parseToken(refreshToken, adminSecret);
//        Integer userId = Integer.valueOf(claims.get("id").toString());
//        Employee employee = employeeService.addEmployeeStation(userId,BeanUtil.toBean(form,AddEmployeeUserParam.class));
//        return Result.newInstance(Employee.class).setData(employee).setMessage("新增成功，初始密码：123456");
//    }

}

